package com.huawei.basic.service.impl;

<<<<<<< HEAD
import com.alibaba.fastjson.JSONObject;
import com.huawei.basic.constant.BaseConstants;
import com.huawei.basic.dto.LoginDto;
import com.huawei.basic.dto.WechatDto;
import com.huawei.basic.exception.BusinessException;
import com.huawei.basic.jwt.JwtUtils;
import com.huawei.basic.jwt.LoginSuccessObj;
import com.huawei.basic.jwt.RsaUtils;
import com.huawei.basic.service.ILoginService;
import com.huawei.basic.utils.AjaxResult;
import com.huawei.basic.utils.HttpClientUtils;
import com.huawei.basic.utils.MD5Utils;
import com.huawei.basic.utils.StrUtils;
import com.huawei.system.domain.Menu;
import com.huawei.system.mapper.MenuMapper;
import com.huawei.system.mapper.PermissionMapper;
import com.huawei.user.domain.Logininfo;
import com.huawei.user.domain.User;
import com.huawei.user.domain.Wxuser;
import com.huawei.user.mapper.LogininfoMapper;
import com.huawei.user.mapper.UserMapper;
import com.huawei.user.mapper.WxuserMapper;
import org.springframework.beans.BeanUtils;
=======
import com.huawei.basic.dto.LoginDto;
import com.huawei.basic.exception.BusinessException;
import com.huawei.basic.service.ILoginService;
import com.huawei.basic.utils.MD5Utils;
import com.huawei.user.domain.Logininfo;
import com.huawei.user.mapper.LogininfoMapper;
>>>>>>> 815a078707a159f81958d10b606db1f81992e9cf
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

<<<<<<< HEAD
import java.awt.*;
import java.security.PrivateKey;
import java.util.HashMap;
import java.util.List;
=======
import java.util.HashMap;
>>>>>>> 815a078707a159f81958d10b606db1f81992e9cf
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
@Transactional(readOnly = true,propagation = Propagation.SUPPORTS)
public class LoginServiceImpl implements ILoginService {
<<<<<<< HEAD

    @Autowired
    private LogininfoMapper logininfoMapper;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private WxuserMapper wxuserMapper;
    @Autowired
    private UserMapper userMapper;

    @Autowired
    private PermissionMapper permissionMapper;
    @Autowired
    private MenuMapper menuMapper;



=======
    
    @Autowired
    private LogininfoMapper logininfoMapper;
    
    @Autowired
    private RedisTemplate redisTemplate;
    
>>>>>>> 815a078707a159f81958d10b606db1f81992e9cf
    @Override
    public Map<String, Object> account(LoginDto dto) {
        String username = dto.getUsername();
        Integer type = dto.getType();
        String password = dto.getPassword();
<<<<<<< HEAD

        if(StringUtils.isEmpty(username)
                || StringUtils.isEmpty(type)
                || StringUtils.isEmpty(password)){// 项目六可使用断言来替代if
            throw new BusinessException("参数不能为空！！");
        }
        //1.根据用户名查询t_logininfo  同时匹配 username phone email
        Logininfo logininfoTmp = logininfoMapper.loadByUsernameAndType(username,type);
        if(logininfoTmp == null){
            throw new BusinessException("账号或密码错误！！");
        }
        //2.比对密码
        String salt = logininfoTmp.getSalt();
        String md5pwd = MD5Utils.encrypByMd5(password + salt);
        if(!logininfoTmp.getPassword().equals(md5pwd)){
            throw new BusinessException("账号或密码错误！！");
        }
        //处理登录成功之后的逻辑
        return loginSuccessHandler(logininfoTmp);




        //3.存储reids
        /*String token = UUID.randomUUID().toString();//UUID字符串
        redisTemplate.opsForValue().set(
                token,
                logininfoTmp,//存储对象一定要序列化
                30,
                TimeUnit.MINUTES
        );
        //4.返回token + logininfo基本信息
        Map<String, Object> map = new HashMap<>();
        map.put("token",token);
        //我们是高级技师，应该需要考虑到数据的安全性  将一些敏感信息置空
        logininfoTmp.setSalt(null);
        logininfoTmp.setPassword(null);
        map.put("logininfo",logininfoTmp);
        return map;*/
    }

    /**
     * 处理登录成功之后的逻辑
     * 1.只有员工需要查询当前登录人对应的菜单权限和按钮权限
     * 2.把他们生成JWT串，然后返回给前端
     * 3.由于前端我们没写解密逻辑，所以这里还要附带把菜单权限和按钮权限也直接返回
     * @param logininfoTmp
     */
    private Map<String, Object> loginSuccessHandler(Logininfo logininfoTmp) {
        LoginSuccessObj loginSuccessObj = new LoginSuccessObj();
        loginSuccessObj.setLogininfo(logininfoTmp);
        if(logininfoTmp.getType()==0){
            //当前登录人所拥有的按钮权限
            List<String> permissions =
                    permissionMapper.loadOwnPermissionsByLogininfoId(logininfoTmp.getId());
            //当前登录人拥有的菜单权限--顶级菜单List
            List<Menu> menus = menuMapper.loadOwnMenusByLoginInfoId(logininfoTmp.getId());
            loginSuccessObj.setMenus(menus);
            loginSuccessObj.setPermissions(permissions);
        }
        //把loginSuccessObj 生成JWT串
        try {
            //读取私钥
            PrivateKey privateKey = RsaUtils.getPrivateKey(JwtUtils.class.getClassLoader().getResource("hrm_auth_rsa").getFile());
            //使用私钥加密
            String jwtStr = JwtUtils.generateTokenExpireInMinutes(loginSuccessObj, privateKey, 30);
            Map<String, Object> map = new HashMap<>();
            map.put("token",jwtStr);
            //我们是高级技师，应该需要考虑到数据的安全性  将一些敏感信息置空
            logininfoTmp.setSalt(null);
            logininfoTmp.setPassword(null);
            map.put("logininfo",logininfoTmp);//当前登录人
            map.put("menus",loginSuccessObj.getMenus());//当前登录人的菜单
            map.put("permissions",loginSuccessObj.getPermissions());//当前登录人的按钮权限
            return map;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    @Override
    public AjaxResult wechat(WechatDto dto) {
        String code = dto.getCode();
        if(StringUtils.isEmpty(code)){
            throw new BusinessException("授权码为空！！");
        }
//        1.根据code，发送http请求从微信获取token          ②请求
        String tokenURL = BaseConstants.WechatConstants.GET_TOKEN_URL
                .replace("APPID",BaseConstants.WechatConstants.APPID)
                .replace("SECRET",BaseConstants.WechatConstants.SECRET)
                .replace("CODE",code);
        String tokenObjStr = HttpClientUtils.httpGet(tokenURL);
        JSONObject tokenObj = JSONObject.parseObject(tokenObjStr);
        String accessToken = tokenObj.getString("access_token");
        String openId = tokenObj.getString("openid");
//        2.拿到token + openId，根据openId查询t_wxuser表
        Wxuser wxuser = wxuserMapper.loadByOpenId(openId);
//        3.是否wxUser存在且绑定了userId
        if(wxuser != null && wxuser.getUserId() != null){
//        3.1 是 直接免密登录
            Logininfo logininfoTmp = logininfoMapper.loadByUserId(wxuser.getUserId());//链表查询
            //3.存储reids
            /*String token = UUID.randomUUID().toString();//UUID字符串
            redisTemplate.opsForValue().set(
                    token,
                    logininfoTmp,//存储对象一定要序列化
                    30,
                    TimeUnit.MINUTES
            );
            //4.返回token + logininfo基本信息
            Map<String, Object> map = new HashMap<>();
            map.put("token",token);
            //我们是高级技师，应该需要考虑到数据的安全性  将一些敏感信息置空
            logininfoTmp.setSalt(null);
            logininfoTmp.setPassword(null);
            map.put("logininfo",logininfoTmp);*/
            //处理登录成功之后的逻辑
            Map<String, Object> map = loginSuccessHandler(logininfoTmp);
            return AjaxResult.success().setResultObj(map);
        }
//        3.2 否 应该定位到绑定页面，让客人自己输入绑定账号
//        注意：需要写到token + openId给callback.html 方便后面获取微信用户信息
        String binderParams = "?accessToken="+accessToken+"&openId="+openId;
        Map<String, Object> map = new HashMap<>();
        map.put("binderParams",binderParams);//跳到绑定页面需要的参数
        return AjaxResult.error().setResultObj(map);
    }

    @Override
    public Map<String, Object> binder(WechatDto dto) {
        //校验验证码
        //。验证码是否有效
        String key = BaseConstants.SmsCodeConstants.BUSINESS_BINDER_PREFIX+dto.getPhone();
        Object smsCodeTmp = redisTemplate.opsForValue().get(key);
        if(smsCodeTmp == null){// 9527:46978465489741
            throw new BusinessException("短信验证码已失效，请重新获取！！！");
        }
        String smsCode = smsCodeTmp.toString().split(":")[0];
        if(!dto.getVerifyCode().equalsIgnoreCase(smsCode)){
            throw new BusinessException("验证码输入错误！！！！");
        }
//        1.根据username判断用户是否已经注册
        Logininfo logininfo = logininfoMapper.loadByUsernameAndType(dto.getPhone(), 1);
        //一个人可以绑定多个微信
        User user = null;
        if(logininfo == null){
//        3.没有注册 生成新的t_user t_logininfo
            user = dto2User(dto.getPhone());
            logininfo = user2Logininfo(user);
            //。先保存t_loginiinfo  返回自增ID
            logininfoMapper.save(logininfo);
            //。设置loginingoId 并保存user
            user.setLogininfoId(logininfo.getId());
            userMapper.save(user);
        }else{
//        2.注册了  查询用户
            user = userMapper.loadByLogininfoId(logininfo.getId());
        }
//  到了这里一定生成了平台的用户了

        String wxUserUrl = BaseConstants.WechatConstants.GET_WXUSER_URL
                .replace("ACCESS_TOKEN",dto.getAccessToken())
                .replace("OPENID",dto.getOpenId());
//        4.拼接token + openId 从微信获取微信的用户基本信息    ③请求
        String wxUserStr = HttpClientUtils.httpGet(wxUserUrl);
        Wxuser wxuser = JSONObject.parseObject(wxUserStr, Wxuser.class);
//        5.绑定t_wxuser和t_user
        wxuser.setUserId(user.getId());
        wxuserMapper.save(wxuser);
//        6.免密登录即可
        return loginSuccessHandler(logininfo);
        //3.存储reids
        /*String token = UUID.randomUUID().toString();//UUID字符串
        redisTemplate.opsForValue().set(
                token,
                logininfo,//存储对象一定要序列化
                30,
                TimeUnit.MINUTES
        );
        //4.返回token + logininfo基本信息
        Map<String, Object> map = new HashMap<>();
        map.put("token",token);
        //我们是高级技师，应该需要考虑到数据的安全性  将一些敏感信息置空
        logininfo.setSalt(null);
        logininfo.setPassword(null);
        map.put("logininfo",logininfo);
        return map;*/
    }

    private Logininfo user2Logininfo(User user) {
        Logininfo logininfo = new Logininfo();
        BeanUtils.copyProperties(user,logininfo);
        logininfo.setType(1);//一定要设置type
        return logininfo;
    }

    private User dto2User(String phone) {
        User user = new User();
        user.setUsername(phone);
        user.setPhone(phone);
        String salt = StrUtils.getComplexRandomString(32);
        //这里需要发送一个短信，通知顾客，让它扫码登录之后去修改自己的默认密码
        String md5pwd = MD5Utils.encrypByMd5("1" + salt);
        user.setSalt(salt);//加密的时候使用的盐值保存到数据
        user.setPassword(md5pwd);//加密之后的密码，保存到数据库
        return user;
=======
        if (StringUtils.isEmpty(username) 
                || StringUtils.isEmpty(type) 
                || StringUtils.isEmpty(password)){
            throw new BusinessException("参数不能为空");
        }
        // 根据用户名查询t_logininfo 同时匹配 username email phone
        Logininfo logininfoTmp = logininfoMapper.loadByUsernameAndType(username,type);
        if (logininfoTmp == null){
            throw new BusinessException("账号或密码错误！");
        }
        // 密码进行对比
        String salt = logininfoTmp.getSalt();
        String md5pwd = MD5Utils.encrypByMd5(password + salt);
        if (!logininfoTmp.getPassword().equals(md5pwd)){
            throw new BusinessException("账号或密码错误！");
        }
        // 存贮reids

        String token = UUID.randomUUID().toString();
        redisTemplate.opsForValue().set(
                token,
                logininfoTmp,
                30,
                TimeUnit.MINUTES
        );
        // 返回token 和logininfo的基本信息
        Map<String, Object> map = new HashMap<>();
        logininfoTmp.setSalt(null);
        logininfoTmp.setPassword(null);
        map.put("token",token);
        map.put("logininfo",logininfoTmp);
        return map; 
>>>>>>> 815a078707a159f81958d10b606db1f81992e9cf
    }
    
} 